Vue.component('upload-images', {
    template: `<el-upload class="upload-demo" :show-file-list="false" accept="image/*" drag :on-change="upload" :auto-upload="false" action="" multiple>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">
            只能上传jpg/png文件
            <el-slider :min="1" v-model="quality" :format-tooltip="formatTooltip"></el-slider>
            <div v-show="quality < 100">当前图片压缩至{{quality}}%</div>
        </div>
    </el-upload>
    `,
    props: ['data'],
    data() {
        return {
            quality: 100,
        }
    },
    methods: {
        formatTooltip(val) {
            return '图片压缩比例：' + val + '%';
        },
        upload({ raw }) {
            const that = this;
            new Compressor(raw, {
                quality: that.quality / 100,
                success(file) {
                    const isJPGorPNG = file.type === 'image/jpeg' || file.type === 'image/png';
                    const isLt500K = file.size / 1024 / 1024 < 10; // 500KB  
                    if (!isJPGorPNG) {
                        that.$message({
                            message: '上传头像图片只能是 JPG/PNG 格式!',
                            type: 'warning'
                        })
                        return false;
                    }
                    if (!isLt500K) {
                        that.$message({
                            message: '上传图片大小不能超过 10MB! 可压缩后上传',
                            type: 'warning'
                        })
                        return false;
                    }
                    const formData = new FormData();
                    formData.append('file', file, file.name);
                    let oFileReader = new FileReader();
                    oFileReader.readAsDataURL(file);
                    oFileReader.onload = function (e) {
                        $.ajax({
                            headers: requestHeaders("JSON"),
                            url: `${BASE_URL2}/generalBusiness/generalSaveFilesAsImage`,
                            type: 'POST',
                            data: JSON.stringify({
                                Data: e.target.result,
                                DataLength: file.size,
                                FileName: file.name
                            }),
                            complete: function (XMLHttpRequest) {
                                requestPretreatment(XMLHttpRequest);
                            },
                            success: function (Result) {
                                if (Result.Status == "success") {
                                    that.$message.success('上传成功')
                                    that.data.push({
                                        Base64: e.target.result,
                                        Picture_URL: Result.FileName,
                                        Picture_Type: 0,
                                    })
                                } else {
                                    that.$message.error('上传失败')
                                }
                            },
                            error: function () {
                                that.$message.error("操作失败，请稍后再试")
                            },
                            dataType: "json"
                        });
                    }
                },
            });
        }
    }
})
new Vue({
    el: '#app',
    data() {
        return {
            form: {
                Article_SerialNumber: '',//商品主键
                Article_Name: '',//商品名称
                Article_Code: '',
                Brand_SerialNumber: '',//商品品牌
                Category_SerialNumber: '',//商品类别
                Series_SerialNumber: '',//商品系列
                Item_SerialNumber: '',//商品款型
                Unit_Price: 0,//吊牌价
                Picture_URL: '',//封面图
                Unify_Unit_Price: '0',
                ClassifyJSON: '',
                JDCOM_Unit_Price: '',
                JDCOM_URL: '',
                Group:'否',
                Children: {
                    business_article_specifications: [{
                        Article_Specifications_SerialNumber: '',//规格主键
                        Article_SerialNumber: '',
                        Specifications_Name: '',//规格名称
                        Unit_Price: 0,//吊牌价
                        SKU_Quantity: '',//SKU数量
                        Picture_URL: '',//规格图片
                        Size:'',
                        Weight: '',//重量
                        Weight_Unit: '',//单位      
                        JDCOM_Unit_Price: '',//吊牌价
                        JDCOM_URL: '',//京东路径
                        Package_Quantity: '',//包装数量
                        SKU_Package_Size: '',//包装尺寸
                        Carton_Quantity: '',//大包装数量
                        Children_Specifications_SerialNumber: '',
                    }],
                    business_article_pic: [],//商品图片
                    business_article_classify: [],
                }
            },
            rules: {
                Article_Name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
                Brand_SerialNumber: [{ required: true, message: '请选择商品品牌', trigger: 'change' }],
                // Unit_Price: [{ required: true, message: '请输入商品吊牌价', trigger: 'change' }],
                Specifications_Name: [{ required: true, message: '请输入规格名称', trigger: 'blur' }],
                // SKU_Quantity: [{ required: true, message: '请输入SKU数量', trigger: 'blur' }]
            },
            Main_Image: [],
            Detail_Image: [],
            brand: [],//品牌
            category: [],//类别
            series: [],//系列
            item: [],//款型
            unit: [],//单位
            classify: [],
            business_article_classify: [],
            defaultProps: {
                children: 'Children',
                label: 'Classify_Name',
                value: 'Classify_SerialNumber',
                multiple: true,
            },
            loading: false,
            isMainSort: false,//主图排序
            isDetailSort: false,//详情图排序
            MainSortable: null,//主图拖拽
            DetailSortable: null,//详情图拖拽
        }
    },
    mounted() {
        const Article_SerialNumber = sessionStorage.getItem("Article_SerialNumber")
        this.getData(Article_SerialNumber);
        this.sortable(this, '#Main_Image', '.preview', 'Main_Image', 'MainSortable');
        this.sortable(this, '#Detail_Image', '.preview', 'Detail_Image', 'DetailSortable');
    },
    computed: {
        is() {
            return function (i, item) {//判断当前规格是否可当子规格
                try {
                    let b1 = i.Row_Status != '1',//没被删
                        b2 = i.Article_Specifications_SerialNumber != '',//已存在
                        b3 = i.Article_Specifications_SerialNumber != item.Article_Specifications_SerialNumber;//不是自己
                    return b1 && b2 && b3;
                } catch (error) {
                    return false;
                }
            }
        }
    },
    watch: {
        isMainSort(val) {
            this.MainSortable.option('disabled', !val);
        },
        isDetailSort(val) {
            this.DetailSortable.option('disabled', !val);
        },
        'form.Unit_Price': function (val) {
            if (this.form.Unify_Unit_Price == '1') {
                this.form.Children.business_article_specifications.forEach(item => {
                    item.Unit_Price = val;
                })
            }
        },
        'form.Unify_Unit_Price': function (val) {
            if (val == '1') {
                this.form.Children.business_article_specifications.forEach(item => {
                    item.Unit_Price = this.form.Unit_Price;
                })
            }
        }
    },
    methods: {
        getData(DocumentSerialNumber) {
            const that = this;
            const Condition = "";
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryByTableName`,
                type: 'POST',
                data: {
                    Data: 'business_brand',
                    Condition,
                },
                success: function (res) {
                    that.brand = res;
                },
                complete: function (XMLHttpRequest) {
                    that.loading = false
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryByTableName`,
                type: 'POST',
                data: {
                    Data: 'business_category',
                    Condition,
                },
                success: function (res) {
                    that.category = res;
                },
                complete: function (XMLHttpRequest) {
                    that.loading = false
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            })
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryByTableName`,
                type: 'POST',
                data: {
                    Data: 'business_series',
                    Condition,
                },
                success: function (res) {
                    that.series = res;
                },
                complete: function (XMLHttpRequest) {
                    that.loading = false
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            })
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryByTableName`,
                type: 'POST',
                data: {
                    Data: 'business_item',
                    Condition,
                },
                success: function (res) {
                    that.item = res;
                },
                complete: function (XMLHttpRequest) {
                    that.loading = false
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            })
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryByTableName`,
                type: 'POST',
                data: {
                    Data: 'business_article_unit',
                    Condition,
                },
                success: function (res) {
                    that.unit = res;
                },
                complete: function (XMLHttpRequest) {
                    that.loading = false
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            })
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/getAllClassify`,
                type: 'GET',
                success: function (data) {
                    that.classify = data
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalGetDataStructure`,
                type: 'POST',
                data: {
                    DocumentSerialNumber,
                    Data: JSON.stringify({ business_article_info: { business_article_pic: {}, business_article_specifications: {}, business_article_classify: {} } }),
                    Condition:"Row_Status='0'"
                },
                success: function ({ business_article_info }) {
                    if (business_article_info.length == 1) {
                        that.form = business_article_info[0];
                        if (that.form.ClassifyJSON) {
                            that.business_article_classify = that.form.ClassifyJSON;
                        }
                        that.form.Children.business_article_pic.forEach(item => {
                            if (item.Picture_Type == '0') {//主图
                                that.Main_Image.push(item)
                            } else {//详情图
                                that.Detail_Image.push(item);
                            }
                        })
                        //冒泡排序
                        sort(that.Main_Image,'Picture_Order');
                        sort(that.Detail_Image,'Picture_Order');
                    }
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
        },
        submitForm(formName) {
            const that = this
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    that.loading = true;
                    //将不存在的图片删除
                    that.Main_Image.filter(i=>i.Row_Status!='1').forEach((item, index) => {//主图
                        if (!Object.keys(item).some(item => item.includes('_Original'))) {//新图片
                            that.form.Children.business_article_pic.push({
                                Article_PicNumber: '',
                                Article_SerialNumber: that.form.Article_SerialNumber,
                                Picture_Type: '0',
                                Picture_Order: index + 1,
                                Picture_URL: item.Picture_URL
                            })
                        } else {//老图片
                            let obj = that.form.Children.business_article_pic.filter(i => i.Article_PicNumber == item.Article_PicNumber)[0];
                            obj.Picture_Order = index + 1;
                            obj.Picture_URL = item.Picture_URL
                        }
                    })
                    that.Detail_Image.forEach((item, index) => {//详情图
                        if (!Object.keys(item).some(item => item.includes('_Original'))) {//新图片
                            that.form.Children.business_article_pic.push({
                                Article_PicNumber: '',
                                Article_SerialNumber: that.form.Article_SerialNumber,
                                Picture_Type: '1',
                                Picture_Order: index + 1,
                                Picture_URL: item.Picture_URL
                            })
                        } else {//老图片
                            let obj = that.form.Children.business_article_pic.filter(i => i.Article_PicNumber == item.Article_PicNumber)[0];
                            obj.Picture_Order = index + 1;
                            obj.Picture_URL = item.Picture_URL
                        }
                    })
                    that.form.ClassifyJSON = JSON.stringify(that.business_article_classify);
                    let arr = [];
                    that.business_article_classify.forEach(Array => {
                        Array.forEach(i => {
                            arr.push({
                                Article_Classify_SerialNumber: '',
                                Article_SerialNumber: that.form.Article_SerialNumber,
                                Classify_SerialNumber: i,
                                Parent_SerialNumber: Array[0],
                            })
                        })
                    })
                    that.form.Children.business_article_classify.forEach(item => {
                        if (!arr.some(i => i.Classify_SerialNumber == item.Classify_SerialNumber)) {//一样
                            item.Row_Status = '1'
                        }
                    })
                    arr.forEach(item => {
                        if (!that.form.Children.business_article_classify.some(i => i.Classify_SerialNumber == item.Classify_SerialNumber)) {
                            that.form.Children.business_article_classify.push(item);
                        }
                    })
                    const { add, modify } = that.deal()
                    let data = {}
                    if (add == null) {
                        data = { Data: JSON.stringify({ 
                            Modify: { business_article_info: [modify] } ,
                            Add:{
                                base_operation_log:[generateLog('修改商品主数据', '平台端操作', 'business_article_info', JSON.stringify({  Modify: { business_article_info: [modify] } }))]
                            }
                        }) }
                    } else {
                        data = {
                            Data: JSON.stringify({ 
                                Modify: { business_article_info: [modify] }, 
                                Add: { 
                                    business_article_info: [add] ,
                                    base_operation_log:[generateLog('修改商品主数据', '平台端操作', 'business_article_info', JSON.stringify({  Modify: { business_article_info: [modify] },Add:{business_article_info: [add]} }))]
                                } 
                            }),
                        }
                    }
                    $.ajax({
                        headers: requestHeaders(),
                        url: `${BASE_URL2}/generalBusiness/generalSave`,
                        type: 'POST',
                        data,
                        success: function (res) {
                            if (res.Status === 'success') {
                                that.$message.success("提交成功");
                                window.history.go(-1);
                            } else {
                                that.$message.error("提交失败，请稍后再试");
                            }
                        },
                        complete: function (XMLHttpRequest) {
                            that.loading = false
                            requestPretreatment(XMLHttpRequest, that);
                        },
                        dataType: "json"
                    })
                } else {
                    that.$message({
                        message: sumberError,
                        type: 'warning'
                    })
                    return false;
                }
            });
        },
        deal() {
            const add = deepClone(this.form)
            const modify = deepClone(this.form)

            let add_business_article_pic = [], modify_business_article_pic = []
            let add_business_article_specifications = [], modify_business_article_specifications = [];
            let add_business_article_classify = [], modify_business_article_classify = [];

            for (const i in modify.Children.business_article_pic) {
                const obj = modify.Children.business_article_pic[i];
                if (!Object.keys(obj).some(item => item.includes('_Original'))) {
                    add_business_article_pic.push(obj)
                } else {
                    modify_business_article_pic.push(obj)
                }
            }
            for (const i in modify.Children.business_article_specifications) {
                const obj = modify.Children.business_article_specifications[i];
                if (!Object.keys(obj).some(item => item.includes('_Original'))) {
                    add_business_article_specifications.push(obj)
                } else {
                    modify_business_article_specifications.push(obj)
                }
            }

            for (const i in modify.Children.business_article_classify) {
                const obj = modify.Children.business_article_classify[i];
                if (!Object.keys(obj).some(item => item.includes('_Original'))) {
                    add_business_article_classify.push(obj)
                } else {
                    modify_business_article_classify.push(obj)
                }
            }

            add.Children.business_article_pic = add_business_article_pic
            modify.Children.business_article_pic = modify_business_article_pic

            add.Children.business_article_specifications = add_business_article_specifications
            modify.Children.business_article_specifications = modify_business_article_specifications

            add.Children.business_article_classify = add_business_article_classify
            modify.Children.business_article_classify = modify_business_article_classify

            if (add_business_article_pic.length == 0 && add_business_article_specifications.length == 0 && add_business_article_classify.length == 0) {
                return { add: null, modify };
            }
            return { add, modify };
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
        add_article_specifications() {//添加规格
            this.form.Children.business_article_specifications.push({
                Article_Specifications_SerialNumber: '',//规格主键
                Article_SerialNumber: this.form.Article_SerialNumber,
                Specifications_Name: '',//规格名称
                Unit_Price: this.form.Unify_Unit_Price == '0' ? 0 : this.form.Unit_Price,//吊牌价
                SKU_Quantity: '',//SKU数量
                Size:'',
                Weight: '',//重量
                Weight_Unit: '',//单位
                JDCOM_Unit_Price: '',
                JDCOM_URL: '',
                Package_Quantity: '',//包装数量
                SKU_Package_Size: '',//包装尺寸
                Carton_Quantity: '',//大包装数量
                Children_Specifications_SerialNumber: ''
            })
        },
        remove_article_specifications() {//删除规格
            if (this.form.Children.business_article_specifications.filter(item => item.Row_Status != '1').length > 1) {//必须至少剩1个
                let i = this.form.Children.business_article_specifications.filter(item => item.Row_Status != '1').length - 1
                let obj = this.form.Children.business_article_specifications.filter(item => item.Row_Status != '1')[i]
                if (!Object.keys(obj).some(item => item.includes('_Original'))) {
                    this.form.Children.business_article_specifications.pop()
                } else {
                    this.$confirm('该操作将删除此规格,是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning',
                    }).then(() => {
                        this.form.Children.business_article_specifications.filter(item => item.Row_Status != '1')[i].Row_Status = '1'
                    }).catch(() => {
                        this.$message({
                            type: 'warning',
                            message: '已取消删除'
                        });
                    });
                }
            } else {
                this.$message({
                    message: '不能在删除了',
                    type: 'warning'
                })
            }
        },
        handleImgClick(formName) {//点击查看图片
            this.$refs[formName][0].showViewer = true;
        },
        RemoveImage(formName, index, item) {//删除图片
            if (!Object.keys(item).some(item => item.includes('_Original'))) {
                let removeimage = this[formName].filter(i=>i.Row_Status=='1');
                let image = this[formName].filter(i=>i.Row_Status!='1');
                image.splice(index, 1)
                this[formName] = [...image,...removeimage];
            } else {
                this.$confirm('是否要删除该图片?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(() => {
                    this[formName].filter(i=>i.Row_Status!='1')[index].Row_Status = '1';
                }).catch(() => { });
            }
        },
        sortable(that, container, element, jsonarray, className, callback) {//拖拽class配置
            var $ul = that.$el.querySelector(container)
            $ul.addEventListener('selectstart', function (e) {
                e.preventDefault();
            })
            this[className] = Sortable.create($ul, {
                handle: element,
                draggable: element,
                animation: 150,
                onUpdate: (event) => {
                    let newIndex = event.newIndex, oldIndex = event.oldIndex;
                    $li = $ul.children[newIndex],
                        $oldLi = $ul.children[oldIndex]
                    //先删除移动的节点, 再插入移动的节点到原有节点，还原了移动的操作
                    $ul.removeChild($li)
                    if (newIndex > oldIndex) {
                        $ul.insertBefore($li, $oldLi)
                    } else {
                        $ul.insertBefore($li, $oldLi.nextSibling)
                    }
                    //通过改变vue遍历数组移动节点
                    let removearray = this[jsonarray].filter(i=>i.Row_Status=='1')
                    let array =  this[jsonarray].filter(i=>i.Row_Status!='1')
                    let item = array[oldIndex];
                    array.splice(oldIndex, 1);
                    array.splice(newIndex, 0, item);
                    this[jsonarray] = [...array,...removearray];
                    if (callback) callback(newIndex, oldIndex);
                }
            })
            this[className].option('disabled', true);
        }
    }
})